////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// The MIT License (MIT)                                                      //
//                                                                            //
// Copyright (c) 2013 Charles Teague                                          //
//                                                                            //
// Permission is hereby granted, free of charge, to any person obtaining a    //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation  //
// the rights to use, copy, modify, merge, publish, distribute, sublicense,   //
// and/or sell copies of the Software, and to permit persons to whom the      //
// Software is furnished to do so, subject to the following conditions:       //
//                                                                            //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software.                        //
//                                                                            //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,   //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING    //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER        //
// DEALINGS IN THE SOFTWARE.                                                  //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


using RPSDAL;
using RPSDAL.CollectionClasses;
using RPSDAL.EntityClasses;
using RPSDAL.FactoryClasses;
using RPSDAL.HelperClasses;

using SD.LLBLGen.Pro.ORMSupportClasses;



public partial class ContactPageField : System.Web.UI.Page
{    

    protected void Page_Load(object sender, EventArgs e)
    {
        int contactPageFieldId = 0;
        if (!Page.IsPostBack)
        {
            if (Parameters.LoggedUser != -1)
            {
                UserEntity eUser = new UserEntity(Parameters.LoggedUser);
                RoleEntity eRole = new RoleEntity(eUser.RoleId);

                if (!eRole.HasConfigureContactInterface)
                {
                    Parameters.LoggedUser = -1;
                    Response.Redirect("Default.aspx");
                    return;
                }
            }

            cmbFieldType.Attributes.Add("OnChange", "FieldTypeChange(this);");
            btnAddValue.Attributes.Add("OnClick", "return AddValue();");
            btnDelete.Attributes.Add("OnClick", "return RemoveValue()");

            // load contact types
            ContactTypeCollection cContactTypes = new ContactTypeCollection();
            cContactTypes.GetMulti(null);

            lstContactTypes.DataSource = cContactTypes;
            lstContactTypes.DataTextField = ContactTypeFields.Name.Name;
            lstContactTypes.DataValueField = ContactTypeFields.ContactTypeId.Name;
            lstContactTypes.DataBind();           


            // load contact  page field for upload
            if (Request.QueryString["id"] != null)
            {
                try
                {
                    contactPageFieldId = Convert.ToInt32(Global.DecryptString(Request.QueryString["id"].ToString()));
                    ContactPageFieldEntity eContactPageField = new ContactPageFieldEntity(contactPageFieldId);

                    txtName.Text = eContactPageField.Name;

                    cmbFieldType.SelectedValue = eContactPageField.Type.ToString();
                    if (eContactPageField.Type == Parameters.COMBOBOBOX_TYPE)
                    {                    
                        // load combobox values
                        ContactPageDropdownFieldValueCollection cComboboxValues = new ContactPageDropdownFieldValueCollection();
                        IPredicateExpression filter = new PredicateExpression();
                        filter.Add(ContactPageDropdownFieldValueFields.ContactPageFieldId == contactPageFieldId);
                        cComboboxValues.GetMulti(filter);

                        lstComboboxValues.DataSource = cComboboxValues;
                        lstComboboxValues.DataValueField = ContactPageDropdownFieldValueFields.Value.Name;
                        lstComboboxValues.DataTextField = ContactPageDropdownFieldValueFields.Value.Name;
                        lstComboboxValues.DataBind();

                        for (int i = 0; i < cComboboxValues.Count; i++) 
                        {
                            hiddenComboBoxValues.Value += cComboboxValues[i].Value + ";";
                        }
                    }

                    if (eContactPageField.Type == Parameters.TEXTAREA_TYPE)
                    {
                        txtRows.Text = eContactPageField.Rows.ToString();
                        txtColumns.Text = eContactPageField.Columns.ToString();

                    }

                    // set available to contact types
                    AvailableToContactTypeCollection cAvailableToContactType = new AvailableToContactTypeCollection();
                    IPredicateExpression filterAvailable = new PredicateExpression();
                    filterAvailable.Add(AvailableToContactTypeFields.ContactPageFieldId == contactPageFieldId);
                    cAvailableToContactType.GetMulti(filterAvailable);

                    for (int i = 0; i < cAvailableToContactType.Count; i++) 
                    {
                        for (int j=0; j<lstContactTypes.Items.Count; j++)
                        {
                            if (lstContactTypes.Items[j].Value == cAvailableToContactType[i].ContactTypeId.ToString()) 
                            {
                                lstContactTypes.Items[j].Selected = true;
                            }
                        }
                    }
                
                }
                catch { }

            }

        }
    }

    #region methods

    #region save 

    /// <summary>
    /// insert or update "Contact" page fields
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Save(object sender, EventArgs e)
    {
        try
        {
            Global.UserLogSave(Parameters.LoggedUser, "Save Filed From Contact Page");
            int contactPageFieldId = 0;
            ContactPageFieldEntity eContactPageField = new ContactPageFieldEntity();
            if (Request.QueryString["id"] != null)
            {
                try
                {
                    contactPageFieldId = Convert.ToInt32(Global.DecryptString(Request.QueryString["id"].ToString()));
                    eContactPageField = new ContactPageFieldEntity(contactPageFieldId);
                }
                catch { }
            }


            eContactPageField.Name = txtName.Text;
            eContactPageField.Type = Convert.ToInt32(cmbFieldType.SelectedValue);
            eContactPageField.OrderIndex = OrderIndex(contactPageFieldId);

            if (eContactPageField.Type == Parameters.TEXTAREA_TYPE) 
            {
                eContactPageField.Rows = 20;
                eContactPageField.Columns = 25;

                if (txtRows.Text.Trim() != "")
                {
                    eContactPageField.Rows = Convert.ToInt32(txtRows.Text);
                }

                if (txtColumns.Text.Trim() != "") 
                {
                    eContactPageField.Columns = Convert.ToInt32(txtColumns.Text);
                }
            }

            eContactPageField.Save();


            SaveComboboxValues(contactPageFieldId, eContactPageField);
            AvailableToContactTypes(contactPageFieldId, eContactPageField);
            
        }
        catch
        {
            // save action failed;
        }

        Response.Redirect("ContactPageAdministration.aspx");
    }

    #region save combobox values

    /// <summary>
    /// save values of a combobox
    /// </summary>
    /// <param name="contactPageFieldId"></param>
    /// <param name="eContactPageField"></param>
    private void SaveComboboxValues(int contactPageFieldId, ContactPageFieldEntity eContactPageField)
    {

        if (eContactPageField.Type == Parameters.COMBOBOBOX_TYPE)
        {

            // the control is a combobox and it must have default values
            ContactPageDropdownFieldValueCollection cContactPageDropdownFieldValue = new ContactPageDropdownFieldValueCollection();

            if (contactPageFieldId != 0)
            {
                IPredicateExpression filter = new PredicateExpression();
                filter.Add(ContactPageDropdownFieldValueFields.ContactPageFieldId == contactPageFieldId);
                cContactPageDropdownFieldValue.DeleteMulti(filter);
            }



            string[] comboboxValues = hiddenComboBoxValues.Value.Split(';');
            for (int i = 0; i < comboboxValues.Length - 1; i++)
            {
                ContactPageDropdownFieldValueEntity eContactPageDropdownFieldValue = new ContactPageDropdownFieldValueEntity();
                eContactPageDropdownFieldValue.Value = comboboxValues[i];
                eContactPageDropdownFieldValue.ContactPageFieldId = eContactPageField.ContactPageFieldId;
                cContactPageDropdownFieldValue.Add(eContactPageDropdownFieldValue);
            }

            cContactPageDropdownFieldValue.SaveMulti();
        }
    }

    #endregion save combobox values

    #region available to contact types

    /// <summary>
    /// determine what contact types will have this field
    /// </summary>
    /// <param name="contactPageFieldId"></param>
    /// <param name="eContactPageField"></param>
    private void AvailableToContactTypes(int contactPageFieldId,ContactPageFieldEntity eContactPageField) 
    {
        if (contactPageFieldId == 0)
        {
            contactPageFieldId = eContactPageField.ContactPageFieldId;
        }
        else 
        {
            AvailableToContactTypeCollection cAvailableToContactType = new AvailableToContactTypeCollection();
            IPredicateExpression filter = new PredicateExpression();
            filter.Add(AvailableToContactTypeFields.ContactPageFieldId == contactPageFieldId);
            cAvailableToContactType.DeleteMulti(filter);
        }

        for (int i = 0; i < lstContactTypes.Items.Count; i++)
        {
            if (lstContactTypes.Items[i].Selected)
            {
                AvailableToContactTypeEntity eAvailableToContactType = new AvailableToContactTypeEntity();
                eAvailableToContactType.ContactPageFieldId = contactPageFieldId;
                eAvailableToContactType.ContactTypeId = Convert.ToInt32(lstContactTypes.Items[i].Value);
                eAvailableToContactType.Save();
            }
        }
    }

    #endregion available to contact types

    #endregion save


    private int OrderIndex(int contactPageFieldId)
    {
        if (contactPageFieldId == 0)
        {
            // add the new field to the bottom of the page
            ContactPageFieldCollection cContactPageField = new ContactPageFieldCollection();
            cContactPageField.GetMulti(null);

            return cContactPageField.Count + 1;
        }
        else 
        {
            return new ContactPageFieldEntity(contactPageFieldId).OrderIndex;
        }
    }

    protected void Cancel(object sender, EventArgs e)
    {
        Response.Redirect("ContactPageAdministration.aspx");
    }

    #endregion methods
}
